package com.junmo.oauth.module.system.service;


import com.junmo.oauth.module.system.dao.SysUserRepository;
import com.junmo.oauth.module.system.entity.SysUser;
import com.junmo.oauth.utils.BeanUtil;
import com.junmo.oauth.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserService {
    // 1、先引入实体类管理器
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    PasswordEncoder passwordEncoder;

    public SysUser getUserInfo(String username) {
        return sysUserRepository.findByUsername(username);
    }

    public Page<SysUser> page(SysUser search, Pageable pageable) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("username", ExampleMatcher.GenericPropertyMatcher::contains)
                .withMatcher("realName", ExampleMatcher.GenericPropertyMatcher::contains)
                .withMatcher("phone", ExampleMatcher.GenericPropertyMatcher::contains)
                .withMatcher("email", ExampleMatcher.GenericPropertyMatcher::contains)//全部模糊查询，即%{address}%
                .withIgnorePaths("password") //忽略字段，即不管password是什么值都不加入查询条件
                ;
        Example<SysUser> example = Example.of(search,matcher);
        return sysUserRepository.findAll(example,pageable);
    }
    @Transactional
    public R create(SysUser entity) {
        entity.setPassword( passwordEncoder.encode(entity.getPassword()) );
        SysUser repoEntoty = sysUserRepository.findByUsername(entity.getUsername());
        if(repoEntoty!=null) return R.error("用户名已存在！！！");
        SysUser returnEntity=sysUserRepository.save(entity);
        if(returnEntity==null) return R.error("新建用户失败！！！");
        return R.success("success");
    }
    @Transactional
    public R edit(SysUser entity) {
        if(StringUtils.hasText(entity.getPassword()) ) entity.setPassword( passwordEncoder.encode(entity.getPassword()) );
        entity = BeanUtil.copyNullProperties(entity,sysUserRepository.getOne(entity.getUserId()));
        SysUser repoEntoty=sysUserRepository.save(entity);
        if(repoEntoty==null) return R.error("用户不存在！！！");
        return R.success("success");
    }
    @Transactional
    public R deleteByIds(List<Number> ids) {
        ids.removeAll(Collections.singleton(null));
        if(CollectionUtils.isEmpty(ids)) return R.error("error");
        List<Long> list=ids.stream().map(id-> Long.valueOf(String.valueOf(id ))).collect(Collectors.toList());
        sysUserRepository.deleteAll( sysUserRepository.findAllById(list) );
        return R.success("success");
    }
    @Transactional
    public R assignRole(Number userID ,List<Number> roleIds) {
        roleIds.removeAll(Collections.singleton(null));
        String deleteSql = "delete from sys_user_role where user_id="+ userID;
        String insertSql = "insert into sys_user_role (user_id,role_id) select "+userID+" as 'user_id',role_id from sys_role ";
        StringBuilder insertSqlWhere = new StringBuilder(" where role_id in ( ");
        roleIds.forEach(roleId->{
            insertSqlWhere.append(roleId+", ");
        });
        insertSqlWhere.deleteCharAt(insertSqlWhere.lastIndexOf(","));
        insertSql += insertSqlWhere.toString()+" ) ";
        Query deleteQuery = entityManager.createNativeQuery(deleteSql);
        Query insertQuery = entityManager.createNativeQuery(insertSql);
        int deleteResult= deleteQuery.executeUpdate();
        int insertResult= insertQuery.executeUpdate();
        return R.success("成功！！！！");
    }
}
